package net.wicp.tams.plugin.task.git;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;

import net.wicp.tams.common.apiext.PwdUtil;
import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.others.GitUtil;
import net.wicp.tams.plugin.constant.EnvName;

@Mojo(name = "addgit", requiresProject = false, threadSafe = false)
public class AddGit extends AbstractMojo {

	// 生产、预发环境下的用户名、密码，中间用逗号隔开 defaultValue = "maven_build,maven_build"
	@Parameter( required = false, property = "user")
	private String user;

	// 要上传的仓库地址
	@Parameter(property = "repository", required = true)
	private String repository;

	@Parameter(property = "branch", required = true)
	private String branch;

	@Parameter(property = "push", defaultValue = "true", required = false)
	private boolean push;

	@Parameter(property = "key", defaultValue = "foxes@#**udk", required = false)
	private String key;

	@Parameter(defaultValue = "${project}")
	private MavenProject project;

	@Override
	public void execute() throws MojoExecutionException, MojoFailureException {
		if (StringUtil.isNull(user)) {
			if (StringUtil.isNotNull(System.getenv(EnvName.gitUser))) {
				user = PwdUtil.Decrypt3DES(System.getenv(EnvName.gitUser), key);
			} else {
				throw new MojoFailureException(
						"必须传入用户：用户名、密码中间用逗号（,）隔开,也可以把他们加密(ts:pwd)后放到环境变量：" + EnvName.gitUser + " 中");
			}
		}
		String[] userary = user.split(",");
		//getLog().info("-----userary[0]:"+userary[0]+"--userary[1]:"+userary[1]+"---");
		if (ArrayUtils.isEmpty(userary) || userary.length < 2) {
			throw new MojoFailureException("用户格式不对，正确的格式为：用户名,密码");
		}

		try {
			Git git = GitUtil.openOrClone(project.getBasedir().getPath(), repository, branch, userary[0], userary[1]);
			getLog().info("-----打开或者克隆仓库成功-----");
			if (push) {
				GitUtil.push2Master(git, branch, userary[0], userary[1]);
				getLog().info("-----代码合并和推送成功-----");
			} else {
				GitUtil.merge4Master(git, branch);
				getLog().info("-----代码合并成功-----");
			}
		} catch (GitAPIException e) {
			throw new MojoExecutionException("git error: ", e);
		}

	}

}
